//
//  QDPayTypeSettingViewController.swift
//  QDMetroClient
//
//  Created by YueWen on 2019/2/28.
//  Copyright © 2019 YueWen. All rights reserved.
//

import UIKit


/// 支付方式设置的header
final class QDPayTypeSettingHeaderView: UIView {
    
    /// 默认高度
    static let height = CGFloat(308)
    
    /// 支付方式名称
    var title: String = "" {
        willSet {
            titleLabel.text = newValue
            subtitleLabel.text = "\(newValue)先乘后付"
        }
    }
    /// 支付方式头像
    let imageView = UIImageView()
    /// 支付方式列表
    let titleLabel = UILabel()
    /// 简易描述
    let subtitleLabel = UILabel()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        imageView.backgroundColor = .white
        
        titleLabel.text = "支付宝"
        titleLabel.font = Font.semibold.font(size: 24)
        titleLabel.textColor = QDColors.black
        
        subtitleLabel.text = "支付宝先乘后付"
        subtitleLabel.font = Font.light.font(size: 16)
        subtitleLabel.textColor = 179.ritl_color
        
        addSubview(imageView)
        addSubview(titleLabel)
        addSubview(subtitleLabel)
        
        imageView.snp.makeConstraints { (make) in
            make.height.width.equalTo(80)
            make.top.equalToSuperview().offset(60)
            make.centerX.equalToSuperview()
        }
        
        titleLabel.snp.makeConstraints { (make) in
            make.centerX.equalToSuperview()
            make.height.equalTo(33)
            make.top.equalTo(imageView.snp.bottom).offset(10)
        }
        
        subtitleLabel.snp.makeConstraints { (make) in
            make.centerX.equalToSuperview()
            make.height.equalTo(22)
            make.top.equalTo(titleLabel.snp.bottom).offset(4)
        }
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
}


/// 用于设置的cell
final class QDPayTypeSettingCell: NWTableViewCell {
    
    /// 显示设置为默认支付方式的描述
    let titleLabel = UILabel()
    /// 选中的图片
    let selectedImageView = UIImageView()
    
    override func buildView() {
        super.buildView()
        
        titleLabel.font = Font.semibold.font(size: 16)
        titleLabel.text = "设置为默认支付方式"
        titleLabel.textColor = QDColors.black
        
        bottomLineInset.left = 48
        bottomLineInset.right = 48
        bottomLineHeight = 0.5
        bottomLineView.backgroundColor = #colorLiteral(red: 0.9294117647, green: 0.9411764706, blue: 0.9333333333, alpha: 1)
        
        contentView.addSubview(titleLabel)
        contentView.addSubview(selectedImageView)
        
        titleLabel.snp.makeConstraints { (make) in
            make.centerY.equalToSuperview()
            make.height.equalTo(22)
            make.left.equalToSuperview().offset(48)
        }
        
        selectedImageView.snp.makeConstraints { (make) in
            make.width.height.equalTo(24)
            make.centerY.equalTo(titleLabel)
            make.right.equalToSuperview().inset(51)
        }
    }
    
    override func setSelected(_ selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)
        selectedImageView.image = selected ? "cs_select".namedImage : "cs_deselect".namedImage
    }
}





/// 支付方式设置
final class QDPayTypeSettingViewController: NWTableViewController {
    
    /// 是否是默认
    var isDefault: Bool = false
    /// 签约协议的id
    var channelId: String = ""
    /// 支付方式
    var payType: QDPayType = .ALiPay

    /// 支付方式的header
    let headerView = QDPayTypeSettingHeaderView()
    /// 解绑方式按钮
    let removeButton = UIButton()
    
    
    convenience init(channelId: String,payType: QDPayType = .ALiPay, isDefault: Bool = false){
        self.init()
        self.isDefault = isDefault
        self.channelId = channelId
        self.payType = payType
    }
    
    override func loadPropertysAtInitialization() {
        super.loadPropertysAtInitialization()
        
        headerRefreshEnable = false
        footerRefreshEnable = false
        tableView.rowHeight = 54
    }
    
    override func registerTableViewCellsAndReusableView() {
        tableView.register(QDPayTypeSettingCell.self, forCellReuseIdentifier: "cell")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        navigationItem.title = "支付方式设置"
        headerView.ritl_width = ritl_width
        headerView.ritl_height = QDPayTypeSettingHeaderView.height
        tableView.tableHeaderView = headerView
        
        removeButton.adjustsImageWhenHighlighted = false
        removeButton.setTitleColor(#colorLiteral(red: 0.4392156863, green: 0.8392156863, blue: 0.5058823529, alpha: 1), for: .normal)
        removeButton.setTitle("解绑此支付方式", for: .normal)
        removeButton.titleLabel?.textAlignment = .center
        removeButton.titleLabel?.font = Font.semibold.font(size: 16)
        removeButton.layer.cornerRadius = 24
        removeButton.clipsToBounds = true
        removeButton.layer.borderColor = QDColors.theme.cgColor
        removeButton.layer.borderWidth = 0.5
        removeButton.addTarget(self, action: #selector(removePayType), for: .touchUpInside)
        
        tableView.addSubview(removeButton)
        
        removeButton.snp.makeConstraints { (make) in
            make.left.equalToSuperview().offset(48)
            make.height.equalTo(48)
            make.width.equalTo(ritl_width - 48 * 2)
            make.top.equalToSuperview().offset(393)
        }
        
        //设置头部属性
        headerView.imageView.image = payType.payTypeLargeImage.namedImage
        headerView.titleLabel.text = payType.title
        headerView.subtitleLabel.text = "\(payType.title)先乘后付"
        
        if isDefault {
            tableView.selectRow(at: IndexPath(row: 0, section: 0), animated: false, scrollPosition: .none)
        }
    }
    
    //MARk: objc
    
    /// 解除这个方式
    @objc func removePayType(){
        
        //进行alert提示
        let alertViewController = ASPopupController.alert(withTitle: "提醒", message: "解绑支付方式会有4天左右的处理时间，该期间支付方式不能正常使用。")
        
        alertViewController.add(ASPopupAction(title: "解绑", style: .qdMetroCancel, handler: {
            //解绑
            self.relieve()
        }))
        
        alertViewController.add(ASPopupAction(title: "取消", style: .qdMetroCancel, handler: {
            
        }))
            
//            UIAlertController(title: "提醒", message: "解绑支付方式会有4天左右的处理时间，该期间支付方式不能正常使用。", preferredStyle: .alert)
        
//        alertViewController.addAction(UIAlertAction(title: "解绑", style: .destructive, handler: { (action) in
//            //解绑
//            self.relieve()
//        }))
//
//        alertViewController.addAction(UIAlertAction(title: "取消", style: .cancel, handler: { (action) in
//            //取消
//        }))
//
        present(alertViewController, animated: true, completion: nil)
    }
    

    // MARK: UITableViewDataSource
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 1
    }
    
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        return tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
    }
    
    
    //MARK: UITableViewDelegate
    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        
        if isDefault { return; }// 已经是默认的，不需要设置
        
        //进行默认设置
        changeDefault(isDefault: true)
    }
}




extension QDPayTypeSettingViewController {
    
    /// 解约
    private func relieve(){
        print("我就是要解约")
    
        view.showTextHUD(text: "正在请求解约", delayHidden: 6.66)
        QDNetworkingManager.request(url: releasePayTypeUrl, paramteres: ["id":channelId], success: { (msg, data) in
            //
            self.view.showTextHUD(text: msg)
            QDUserInfoModel.share.currentChannel = ""
            //发送通知
            NotificationCenter.default.post(name: QDPayTypeStatusDidChangedNotificationName, object: nil)
            self.navigationController?.popViewController(animated: true)//返回

        }) { (msg, errorType) in
            self.view.showTextHUD(text: msg)
        }
    }
    
    /// 修改默认
    private func changeDefault(isDefault: Bool){
        
        view.showTextHUD(text: "正在修改默认支付方式", delayHidden: 10)
        QDNetworkingManager.requestChangedDefaultChannel(channelId: channelId, complete: {
            
            self.view.showTextHUD(text: "修改默认支付方式成功")
            //修改本地记录位
            print("\n\n\(self.payType.title)\n\n")
            QDUserInfoModel.share.currentChannel = "当前默认\(self.payType.title)"
            //发送通知
            NotificationCenter.default.post(name: QDPayTypeStatusDidChangedNotificationName, object: nil)
            //设置成为默认
            self.tableView.selectRow(at: IndexPath(row: 0, section: 0), animated: true, scrollPosition: .none)
            
        }) { (msg, errorType) in
            
            self.view.showTextHUD(text: msg)
        }
    }
}




extension QDNetworkingManager {
    
    // 请求设置为默认支付方式
    static func requestChangedDefaultChannel(channelId: String, complete:@escaping (()->()),fail: QDNetworkingError? ){
        
        request(url: switchDefaultPayTypeUrl, paramteres: ["id":channelId], success: { (msg, data) in
            
            complete()
            
        }) { (msg, errorType) in
            fail?(msg,errorType)
        }
    }
    
}
